package com.joy.common.interceptor;

import com.joy.web.admin.service.IResourceService;
import com.joy.web.admin.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 判断用户有没有登录、 有没有踢出  附加 第一次访问需要做的事
 *
 */
@Slf4j
@Component
public class LoginInterceptor extends HandlerInterceptorAdapter {

	@Resource
	private IUserService userService;
	@Resource
	private IResourceService resourceService;

	@Override
	public void afterCompletion(HttpServletRequest request,
								HttpServletResponse response, Object handler, Exception ex)
			throws Exception {

	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response,
						   Object handler, ModelAndView mav) throws Exception {


	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		Subject subject = SecurityUtils.getSubject();
		// 判断有没有登录
		if(!subject.isAuthenticated() && ! subject.isRemembered()){
			response.sendRedirect("/login");
			return false;
		}
		String userNm = (String)subject.getPrincipal();
		//如果用户是通过RememberMe登录的，判断一下有没有被锁定
		//第一次，记得写session 中的user_id
		Session session = subject.getSession();
		if(session.getAttribute("firstmark") == null){

			session.setAttribute("firstmark", true);
		}

		return super.preHandle(request, response, handler);
	}
}
